package com.ep.commonbaseadapter.base;

import android.support.v4.util.SparseArrayCompat;

/**
 * Created by Administrator on 2017/7/31.
 */

public class ItemViewDelegateManager<T> {
    SparseArrayCompat<ItemViewDelegate<T>> mDelegates = new SparseArrayCompat<>();

    /**
     * 获取item的数量
     *
     * @return
     */
    public int getItemViewDelegateCount() {
        return mDelegates.size();
    }

    /**
     * 保存ItemViewDelegate
     *
     * @param itemViewDelegate
     * @return
     */
    public ItemViewDelegateManager<T> addItemViewDelete(ItemViewDelegate<T> itemViewDelegate) {
        int viewType = mDelegates.size();
        if (itemViewDelegate != null) {
            mDelegates.put(viewType, itemViewDelegate);
            viewType++;
        }
        return this;
    }

    /**
     * 获取viewType
     *
     * @param data
     * @param position
     * @return
     */
    public int getItemViewType(T data, int position) {
        int delegatesCount = mDelegates.size();
        for (int i = delegatesCount - 1; i >= 0; i--) {
            ItemViewDelegate<T> itemViewDelegate = mDelegates.valueAt(i);
            if (itemViewDelegate.isForViewType(data, position)) {
                return mDelegates.keyAt(i);
            }

        }
        throw new IllegalArgumentException(
                "No ItemViewDelegate added that matches position=" + position + " in data source");
    }


    /**
     * 获取ItemViewDelegate
     *
     * @param data
     * @param position
     * @return
     */
    public ItemViewDelegate<T> getItemViewDelegate(T data, int position) {
        int delegatesCount = mDelegates.size();

        for (int i = delegatesCount - 1; i >= 0; i--) {
            ItemViewDelegate<T> itemViewDelegate = mDelegates.valueAt(i);
            if (itemViewDelegate.isForViewType(data, position)) {
                return itemViewDelegate;
            }

        }
        throw new IllegalArgumentException(
                "No ItemViewDelegate added that matches position=" + position + " in data source");
    }

    /**
     * 绑定数据
     *
     * @param viewHolder
     * @param data
     * @param position
     */
    public void bindData(ViewHolder viewHolder, T data, int position) {
        int delegatesCount = mDelegates.size();

        for (int i = 0; i < delegatesCount; i++) {
            ItemViewDelegate<T> itemViewDelegate = mDelegates.valueAt(i);
            if (itemViewDelegate.isForViewType(data, position)) {
                itemViewDelegate.bindData(viewHolder, data, position);
                return;
            }
        }
        throw new IllegalArgumentException(
                "No ItemViewDelegateManager added that matches position=" + position + " in data source");
    }
}
